﻿using FlaUI.Core.AutomationElements;
using FlaUI.UIA3;
using LVYAN.Utils;
using System;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

namespace Win
{
    public class MainWindow
    {

        /// <summary>
        /// 是否杀死进程
        /// </summary>
        /// <param name="IsKillResetStart"></param>
        public void ResetStart(bool IsKillResetStart = false)
        {
            try
            {

                new MainWindow().Kill();


                IntPtr handle = Process.GetCurrentProcess().MainWindowHandle;
                MainWindowType.SetConsoleMode(handle, MainWindowType.ENABLE_EXTENDED_FLAGS);
                Window window = new MainWindow().GetWindowById(IsKillResetStart);
                if (IsKillResetStart)
                {
                    window.Login();
                    window = new MainWindow().GetWindowById();
                }
                Thread.Sleep(2000);
                window.Top();

                Thread.Sleep(3000);
                Task.Run(() =>
                {
                    while (Console.In.Peek() != -1)
                    {
                        Console.Read();
                        //Console.In.ReadToEndAsync();
                    }
                });
                //机器人
                var Robot = window.RobotInfo();
                //会话消息
                window.EntryRobot(Robot);
            }
            catch (OutOfMemoryException ex)
            {
                new LoggerService().ResponseMsgDebug("主程序", "内存异常", ex.Message);
                new LoggerService().ResponseMsgDebug("主程序", "内存异常", ex);
                Thread.Sleep(5000);
                ResetStart(true);
            }
            catch (Exception ex)
            {
                new LoggerService().ResponseMsgDebug("主程序", "异常", ex.Message);
                new LoggerService().ResponseMsgDebug("主程序", "异常", ex);
                Thread.Sleep(5000);
                ResetStart();
            }

        }

        public Window GetWindowById(bool IsKill = false)
        {
            Thread.Sleep(200);
            int Id = -1;
            if (IsKill) Id = new WinWechat().KillResetStartWechatProcessID();
            else Id = new WinWechat().GetWechatProcessID();
            using (var app = FlaUI.Core.Application.Attach(Id))
            {
                using (var automation = new UIA3Automation())
                {
                    var window = app.GetMainWindow(automation, TimeSpan.FromSeconds(2));
                    if (window == null)
                    {
                        Console.WriteLine("应用已断开");
                        new WinWechat().StartWechatProcessID();

                        Thread.Sleep(2000);
                        return GetWindowById(IsKill);
                    }
                    if (window.Patterns.Window.PatternOrDefault != null)
                    {
                        //将微信窗体设置为默认焦点状态
                        if (window.Patterns.Window.Pattern.WindowVisualState != FlaUI.Core.Definitions.WindowVisualState.Normal)
                        {
                            window.Patterns.Window.Pattern.SetWindowVisualState(FlaUI.Core.Definitions.WindowVisualState.Normal);
                        }
                    }
                    return window;
                }
            }
        }
        /// <summary>
        /// 自杀式-防止启用多个应用
        /// </summary>
        public void Kill()
        {
            Thread.Sleep(200);
            WinProcess winProcess = new WinProcess();
            Process process = Process.GetCurrentProcess();
            winProcess.Kill(process.ProcessName, 1);


        }
        /// <summary>
        /// 重启应用
        /// </summary>
        public void ResetAppStart()
        {
            // 启动新的进程，传递新参数
            //ProcessStartInfo startInfo = new ProcessStartInfo();
            //startInfo.FileName = Assembly.GetExecutingAssembly().Location;
            //startInfo.Arguments = "NewArgument1 NewArgument2";
            WinProcess winProcess = new WinProcess();
            Process process = Process.GetCurrentProcess();
            var Cache = winProcess.GetProcessIDByCacheCount(process.ProcessName);
            var Model = new AIConfig().GetConfigModel(nameof(MainWindow), nameof(ResetAppStart));
            new LoggerService().ResponseMsgDebug("内存", "内存", process.ProcessName + ":" + Cache + ",阈值：" + Model.AppCache);
            if (Cache> Model.AppCache)
            {
                new LoggerService().ResponseMsgDebug("内存重启", "内存重启", process.ProcessName + ":" + Cache + "阈值：" + Model.AppCache);
                Process.Start(process.MainModule.ModuleName);
                // 关闭当前进程
                Environment.Exit(0);
            }
        }
    }
}
